<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/12/7
 * Time: 14:35
 */
class merchant{
    public function index(){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorConfig = M("vendor_config");
        $vendorModel = M("mivendor");
        $miyouquan = M("miyouquan");
        Session::switchCustomer($cid);
        $vid = $vendorModel->where("userId=$userId and deleted=0")->getField("id");
        $configInfo = $vendorConfig->where("cid=$cid")->field("registerRequired,overdueDay,systemName,registerPic,agreementName,agreement,auditRequired,experienceAllowed,menuJson")->find();
        $configInfo['registerPic']=json_decode($configInfo['registerPic'],true);
        if(!$vid){
            $configInfo['agreement'] = nl2br($configInfo['agreement']);
            if($configInfo['registerRequired']){
                Output::instance()->module("merchant","login")->object($configInfo);
                return;
            }else{
                $vid = self::addMivendor($userId);
            }
        }
        $result = $vendorModel->where("id=$vid")->field("id,logo,name,status,certificaTime")->find();
        $menu = json_decode($configInfo['menuJson'],true);
        $result['wxBackImgUrl']=$menu['wx']['backImgUrl'];
        $result['wxMenu'] = json_decode($menu['wx']['menu'],true);
        $result['appMenu'] = json_decode($menu['app']['menu'],true);
        $result['appBackImgUrl']=$menu['app']['backImgUrl'];
        $result['menuJson']['wx']['menu'] = json_decode($result['menuJson']['wx']['menu'],true);
        $result['menuJson']['app']['menu'] = json_decode($result['menuJson']['app']['menu'],true);
        if($result['status']==3){
            $overdueDay = $configInfo['overdueDay'];
            $overdueDay+=30;
            $time  = strtotime("+$overdueDay day ",strtotime($result['certificaTime']));
            if($time<time()) {
                $result['status'] = 6;
            }else{
                $overdueDay = $configInfo['overdueDay'];
                $time  = strtotime("+$overdueDay day ",strtotime($result['certificaTime']));
                if($time<time()){
                    $vendorModel->where(['id'=>$vid])->save(['status'=>4,'certificaTime'=>'','updateTime'=>date("Y-m-d H:i:s",time())]);
                    $result['status'] = 4;
                }
            }
        }
        if($_GET['by']!='app'){
            if(!$configInfo['experienceAllowed']&&($result['status']==0||$result['status']==5||$result['status']==4)){
                self::getVerification($vid);
                return;
            }
        }

        $qid=$miyouquan->alias("a")
            ->where("a.cId=$cid")
            ->getField("a.id");
        $result['qid']=$qid;
        $result['uid']=Session::$user['userId'];
        $result['experienceAllowed']=$configInfo['experienceAllowed'];
        $result['auditRequired']=$configInfo['auditRequired'];
        $result['systemName']=$configInfo['systemName'];
        $result['shareImg']=$configInfo['registerPic'][0]['picUrl'];
        Output::instance()->module("merchant","index")->object($result);
    }
    //不需要注册成为供应商
    private function addMivendor($uid,$channelId=0,$certificationType=0){
        if(!$uid){return;}
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        $vendorConfig =M('vendor_config');
        Session::switchCustomer($cid);
        $weixinInfo = M("user_weixin_info");
        $time = date('Y-m-d H:i:s');
        $userInfo = $weixinInfo->where("userId='$uid'")->field("nickname,headimgurl")->find();

        $vid = $vendorModel->where("userId=$uid and deleted=0")->getField("id");
        if($vid){return $vid;}
        //供应商入库
        $mivendorData = [
            'mId'               => 0,
            'name'              => $userInfo['nickname'],
            'logo'              => $userInfo['headimgurl'],
            'vendorAgent'       => $channelId,
            'createTime'        => $time,
            'updateTime'        => $time,
            'deleted'           => 0,
            'userId'            =>$uid,
            'cId'               =>$cid,
            'certificationType' =>$certificationType
        ];
        $save = $vendorModel->add($mivendorData);
        Log::write('from',$_GET['by']);
        if($_GET['by']){
            $getId = $vendorConfig->where(['cid'=>$cid])->find();
            $arrId = explode(',',$getId['defaultPid']);
            Log::write('ids'.$getId['defaultPid']);
            $result = array();
            foreach ($arrId as $val) {
                $successid = self::copyProductById($val,$save);
                $result['id']=$successid['productId'];
            }
        }
        return  $save;
    }
    //注册成为供应商
    public function addMivendorByReg($name,$companyName,$phone,$province,$city,$areaCode){
        $cid=Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $weixinInfo = M("user_weixin_info");
        $time = date('Y-m-d H:i:s');
        $userInfo = $weixinInfo->where("openid='$userName'")->field("id,nickname,headimgurl")->find();
        $userId = Session::$user['userId'];
        $vid = $vendorModel->where("userId=$userId and deleted=0")->getField("id");
        if($vid){
            Output::instance()->resultCode();
            return;
        }
        while(strlen($areaCode)<4){
            $areaCode='0'.$areaCode;
        };
        $code = $vendorModel->where("cId=$cid and areaCode='$areaCode'")->field("max(serialNumber) as serialNumber")->find();
        if($code){
            $code = substr($code['serialNumber'],-4);
            $code +=1;
        }else{
            $code = 1;
        }
        while(strlen($code)<4){
            $code='0'.$code;
        };
        $serialNumber= $areaCode.$code;
        do{
            $isrepeat= $vendorModel->where("cId=$cid and serialNumber='$serialNumber'")->find();
            if($isrepeat){
                $code+=1;
                while(strlen($code)<4){
                    $code='0'.$code;
                };
                $serialNumber= $areaCode.$code;
            }
        }while($isrepeat);
        $mivendorData = [
            'mId'               => 0,
            'name'              => $name,
            'logo'              => $userInfo['headimgurl'],
            'vendorAgent'       => 0,
            'createTime'        => $time,
            'updateTime'        => $time,
            'deleted'           => 0,
            'userId'            =>$userId,
            'cId'               =>$cid,
            'companyName'       =>$companyName,
            'phone'             =>$phone,
            'province'          =>$province,
            'city'              =>$city,
            'areaCode'          =>$areaCode,
            'serialNumber'      =>$serialNumber
        ];
        $save = $vendorModel->add($mivendorData);
        if($save){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public function storeIndex(){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $vendorInfo = $vendorModel->where("userId = $userId and deleted=0")->field("id,status")->find();
        $vid = $vendorInfo['id'];
        $result = self::getStoreCount($vid);
        $result['vid']=$vid;
        Output::instance()->module("merchant","storeList")->object($result);

    }
    //门店列表
    public function getStoreList($vid,$start=0,$limit=20){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M('store');
        Session::switchCustomer($cid);
        $start = $start*$limit;
        $where['vId']=array("eq",$vid);
        $where['deleted']=array("eq",0);
        $arr = $storeModel->where($where)->field("id,picUrl,name,status")
            ->order("updateTime desc")
            ->limit("$start,$limit")
            ->select();
        if($arr){
            $count = $storeModel->where($where)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }

    //门店详情或者添加门店
    public function getStoreById($id){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $storeModel = M('store');
        $storeService = M("store_service");
        $vendorConfig = M("vendor_config");
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        if($id){
            $result['storeInfo']=$storeModel->where("id=$id")->field("id,picUrl1,name,phone,province,status,city,country,address,longitude,latitude")->find();
            $result['storeInfo']['picUrl1']=json_decode($result['storeInfo']['picUrl1'],true);
            $serviceList = $storeService->alias("a")
                ->join("wx_store_service_list b on a.id=b.serviceId and b.storeId=$id")
                ->field('a.*,IF(b.id is null,"0","1") as checked')
                ->where("a.cid = $cid")->select();
        }else{
            $serviceList = $storeService->where("cid = $cid")->select();
        }
        $vid = $vendorModel->where("userId=$userId and deleted=0")->getField("id");
        $result['systemName']=$vendorConfig->where("cid=$cid")->getField("systemName");
        $result['serviceList']=$serviceList;
        $result['vid']=$vid;
        Output::instance()->module("merchant","storeInfo")->object($result);
    }

    //获得可添加门店的数量
    private function getStoreCount($vid){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModule = M("mivendor");
        $vendorConfig = M("vendor_config");
        $storeModel = M('store');
        Session::switchCustomer($cid);
        $where['vId']=array("eq",$vid);
        $where['deleted']=array("eq",0);
        $vendorInfo = $vendorModule->where("id=$vid")->find();
        $count = $storeModel->where($where)->count();
        $configInfo = $vendorConfig->where("cid=$cid")->field("experienceAllowed,auditRequired,systemName,limitedStroeNum,auditedStoreNum")->find();
        if($configInfo['experienceAllowed']&&$configInfo['auditRequired']){
            if($vendorInfo['status']!=3){
                $storeCount = $configInfo['limitedStroeNum']-$count;
            }else{
                $storeCount = $configInfo['auditedStoreNum']-$count;
            }
        }else if($configInfo['experienceAllowed']||(!$configInfo['experienceAllowed']&&$vendorInfo['status']==3)){
            $storeCount = $configInfo['auditedStoreNum']-$count;
        }else{
            $storeCount=0;
        }
        $configInfo['storeCount']=$storeCount;
        return $configInfo;
    }
    //保存门店
    public function saveStore($name,$phone,$address,$picUrl1,$vid,$province,$city,$country,$service,$id=null,$longitude=null,$latitude=null){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M('store');
        $storeService = M("store_service_list");
        $vendorConfig = M("vendor_config");
        $vendorModel = M("mivendor");
        $storeDistrict = M("store_district");
        $category = M("store_district_category");
        Session::switchCustomer($cid);
        $config = $vendorConfig->where("cid = $cid")->find();
        $canAdd = true;
        if($config['auditRequired']){
            $status  = $vendorModel->where("id=$vid")->getField("status");
            if(!$config['experienceAllowed']&&$status!=3){
                $canAdd = false;
            }else{
                $count = $storeModel->where("vId=$vid and deleted=0")->count();
                if($status!=3){
                    if($count>=$config['limitedStroeNum']){
                        $canAdd = false;
                    }
                }else{
                    if($count>=$config['auditedStoreNum']){
                        $canAdd = false;
                    }
                }
            }
        }
        if(!$id&&!$canAdd){
            Output::instance()->resultCode(1,"可添加门店数量不足!");
            return;
        }
        $data['customerId']=$cid;
        $data['name']=$name;
        $data['phone']=$phone;
        $data['address']=$address;
        $data['picUrl1']=$picUrl1;
        $picUrl1 = json_decode($picUrl1,true);
        $data['picUrl']=$picUrl1[0]['picUrl'];
        $data['vId']=$vid;
        $data['province']=$province;
        $data['city']=$city;
        $data['country']=$country;
        $data['longitude']=$longitude;
        $data['latitude']=$latitude;
        $data['updateTime']=date("Y-m-d H:i:s");
        if($id){
            $storeModel->where("id=$id")->save($data);
        }else{
            $categoryId = $category->where("fromCustomerId = $cid and deleted=0 and name='默认'")->getField("id");
            if(!$categoryId){
                $categoryData['name']='默认';
                $categoryData['fromCustomerId']=$cid;
                $categoryData['updateTime']=date("Y-m-d H:i:s");
                $categoryId= $category->add($categoryData);
            }
            $districtId = $storeDistrict->where("fromCustomerId=$cid and deleted=0 and parentId is null and districtCategoryId=$categoryId")->getField("id");
            if(!$districtId){
                $districtData['name'] = '门店信息';
                $districtData['fromCustomerId'] = $cid;
                $districtData['leaf'] = 0;
                $districtData['updateTime'] = date("Y-m-d H:i:s");
                $districtData['districtCategoryId'] = $categoryId;
                $districtId = $storeDistrict->add($districtData);
            }
            $data['districtId']=$districtId;
            $id = $storeModel->add($data);
        }
        if($service){
            $service = explode(",",$service);
            $storeService->where("storeId=$id")->delete();
            foreach($service as $key=>$value){
                $serviceData[$key]['cid']=$cid;
                $serviceData[$key]['storeId']=$id;
                $serviceData[$key]['serviceId']=$value;
            }
            $storeService->addAll($serviceData);
        }
        Output::instance()->resultCode();
    }
    //认证
    public function getVerification($id,$again=0){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorConfig = M("vendor_config");
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $result['config'] = $vendorConfig->alias("a")
            ->join("wx_module_product b on a.auditCost = b.id")
            ->field("a.id,b.fixedPrice,b.discountedPrice,b.vId,a.auditCost")
            ->where("a.cid = $cid")->find();
        $result['vendorInfo'] = $vendorModel->where("id=$id")->find();
        if($result['vendorInfo']['status']==5&&!$again){
            Output::instance()->module("merchant","verification_fail")->object($result);
        }else{
            if($result['config']['discountedPrice']){
                $result['config']['money']=$result['config']['discountedPrice'];
            }else{
                $result['config']['money']=$result['config']['fixedPrice'];
            }
            Output::instance()->module("merchant","verification")->object($result);
        }
    }

    //保存认证资料
    public function saveVerification($id,$busLicence,$IDPositive,$IDBack,$certificationType,$wxid,$phone){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorConfig = M("vendor_config");
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $configInfo = $vendorConfig->where("cid=$cid")->find();
        $oldStatus = $vendorModel->where("id=$id")->getField('status');
        if($_GET['by']=='app'){
            $data['status']=1;
        }else{
            if(!$configInfo['auditRequired']){
                $data['status']=3;
            }else if($oldStatus>0||!$configInfo['auditCost']){
                $data['status']=1;
            }else if($configInfo['auditCost']){
                $data['status']=0;
            }
        }
        $data['certificationType']=$certificationType;
        $data['wxid']=$wxid;
        $data['busLicence']=$busLicence;
        $data['IDPositive']=$IDPositive;
        $data['IDBack']=$IDBack;
        $phone?$data['phone']=$phone:"";
        $vendorModel->where("id=$id")->save($data);
        Output::instance()->resultCode();
    }
    public function setVendorStatus($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $data['status']=1;
        $vendorModel->where("id=$id")->save($data);
        return;
    }
    //证书
    public function getCertificate(){
        $cid=Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $vendorInfo = $vendorModel->where("userId=$userId and deleted=0")->find();
        $vendorInfo['certificaTime'] = date("Y年m月d日",strtotime($vendorInfo['certificaTime']));
        if($vendorInfo['status']!=3){
            Output::instance()->resultCode(1,"无访问权限");
            return;
        }
        if($vendorInfo['certificaImgUrl']){
            $imgUrl = $vendorInfo['certificaImgUrl'];
        }else{
            $fileName = rand(1000,9999).time();
            $imgUrl = self::createImage($fileName,$vendorInfo['companyName'],$vendorInfo['serialNumber'],$vendorInfo['name'],$vendorInfo['certificaTime']);
            if($imgUrl->code!=0){
                Output::instance()->resultCode($imgUrl->code,$imgUrl->msg);
                return;
            }
            $imgUrl = $imgUrl->path;
            $vendorModel->where("id=".$vendorInfo['id'])->setField("certificaImgUrl",$imgUrl);
        }
        $result['imgUrl']=$imgUrl;
        Output::instance()->module("merchant","certificate")->object($result);

    }
    //删除门店
    public function deletedStore($id){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M("store");
        Session::switchCustomer($cid);
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $storeModel->where("id=$id")->save($data);
        Output::instance()->resultCode();
    }
    /**
     * 重置认证
     * @param $id
     */
    public function resetIdentifice($id)
    {
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $Mivendor = M('mivendor');
        Session::switchCustomer($cid);
        $findMivendor = $Mivendor->field('id,status,IDPositive,IDBack,certificationType,busLicence,wxid,IDName,Message')
            ->where(['id'=>$id])->find();
        if($findMivendor['status']==4)
        {
            $data['IDPositive']='';
            $data['IDBack']='';
            $data['certificationType']='';
            $data['busLicence']='';
            $data['wxid']='';
            $data['IDName']='';
            $data['IDName']='';
            $data['Message']='';
            $data['status']=0;
            $data['phone']='';

            $update = $Mivendor->where(['id'=>$id])->save($data);
            if($update){
                Output::instance()->resultCode();
            }
        }
    }
    private function createImage($fileName,$companyName,$serialNumber,$name,$certificaTime){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorConfig = M("vendor_config");
        Session::switchCustomer($cid);
        $configInfo = $vendorConfig->where("cid=$cid")->find();
        $certificateConfig = json_decode($configInfo['certificateConfig'],true);
        $fname="vendor_$fileName.png";
        $fileName=LOCAL_PIC_PATH . "$fname";
        $img=self::curls($configInfo['certificateBackground']);
        $img=imagecreatefromstring($img);
        if(!$img) {
            $out1 = new stdClass();
            $out1->code=1;
            $out1->msg="背景图片获取错误，请重试";
            return $out1;
        }
        $imgWidth=imagesx($img);
        $imgHeight=imagesy($img);
        $font=__DIR__."/FZLTHJW.TTF";
        //公司名称
        $color = self::hex2rgb($certificateConfig['company']['color']);
        $fontcolor=imagecolorallocate($img,$color['r'],$color['g'],$color['b']);
        $fontsize=$certificateConfig['company']['size'];
//        $fontBox = imagettfbbox($fontsize, 0, $font, $companyName);
        imagettftext($img,$fontsize,0,$certificateConfig['company']['X'],$certificateConfig['company']['Y'],$fontcolor,$font,$companyName);
        //编号
        $color = self::hex2rgb($certificateConfig['serialNumber']['color']);
        $fontcolor=imagecolorallocate($img,$color['r'],$color['g'],$color['b']);
        $fontsize=$certificateConfig['serialNumber']['size'];
        imagettftext($img,$fontsize,0,$certificateConfig['serialNumber']['X'],$certificateConfig['serialNumber']['Y'],$fontcolor,$font,$serialNumber);
        //名字
        $color = self::hex2rgb($certificateConfig['name']['color']);
        $fontcolor=imagecolorallocate($img,$color['r'],$color['g'],$color['b']);
        $fontsize=$certificateConfig['name']['size'];
        imagettftext($img,$fontsize,0,$certificateConfig['name']['X'],$certificateConfig['name']['Y'],$fontcolor,$font,$name);
        //时间
        $color = self::hex2rgb($certificateConfig['time']['color']);
        $fontcolor=imagecolorallocate($img,$color['r'],$color['g'],$color['b']);
        $fontsize=$certificateConfig['time']['size'];
        imagettftext($img,$fontsize,0,$certificateConfig['time']['X'],$certificateConfig['time']['Y'],$fontcolor,$font,$certificaTime);
        imagejpeg($img,$fileName);
        imagedestroy($img);
        if(file_exists($fileName)){
            $out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
            if(!$out->code){
                return $out;
            }
        }
    }
    public function curls($url, $timeout = '10')
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }
    function get_lt_rounder_corner($radius) {
        $img     = imagecreatetruecolor($radius, $radius);  // 创建一个正方形的图像
        $bgcolor    = imagecolorallocate($img, 255, 255, 255);   // 图像的背景
        $fgcolor    = imagecolorallocate($img, 0, 0, 0);
        imagefill($img, 0, 0, $bgcolor);
        imagefilledarc($img, $radius, $radius, $radius*2, $radius*2, 180, 270, $fgcolor, IMG_ARC_PIE);
        imagecolortransparent($img, $fgcolor);
        return $img;
    }
    function autowrap($fontsize, $angle, $fontface, $string, $width) {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        $tempstring = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<mb_strlen($string);$i++) {
            $letter[] = mb_substr($string, $i, 1,"utf8");
        }
        foreach ($letter as $l) {
            $teststr = $content.$l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $tempstring .= "\n";
                $content = "";
            }
            $content .= $l;
            $tempstring.=$l;
        }
        return $tempstring;
    }
    function hex2rgb($hexColor) {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }
    private static function createOrderSerialNumber($ids, $customerId) {
        if (!strstr($ids, ',')) {
            $id = $ids;
        } else {
            // 如果拆单则使用第一个订单的id
            $id = substr($ids,0,strpos($ids,','));
        }

        $length = strlen($id);
        if ($length >= 3) {
            $id = substr($id, -3);
        } else {
            $id = str_pad($id, 3, '0', STR_PAD_LEFT);
        }
        $sn = $customerId . date("ymdHis") . $id;
        return $sn;
    }

    public function copyProductById($id,$vId,$customerId=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $productModule = M("module_product");
        $shareBaseModel=M("mishare");
        $shareMaterModel=M("mishare_material");
        Session::switchCustomer($cid);
        $time = date("Y-m-d H:i:s");
        $productInfo = $productModule->where("id=".$id)->find();
        unset($productInfo["id"]);
        unset($productInfo['salesCount']);
        unset($productInfo['isChainPro']);
        unset($productInfo['supplyChainId']);
        unset($productInfo['supplyProId']);
        unset($productInfo['discountedPrice']);
        unset($productInfo['supplyPrice']);
        unset($productInfo['saleCut']);
        unset($productInfo['vId']);
        unset($productInfo['createPerson']);
        $productInfo['vId']=$vId;
        $customerId?"":$customerId=$cid;
        $cid = $productInfo['fromCustomerId'];
        $productInfo['fromCustomerId']=$customerId;
        $productInfo["createTime"]=$time;
        $productInfo["updateTime"]=$time;
        $productInfo['createPerson']='vendor';

        $newProductId = $productModule->add($productInfo);

        $shareInfo = $shareBaseModel->where("moduleId=".$id." and module = 'product'")->find();
        $shareInfo["moduleId"]=$newProductId;
        $shareBaseId = $shareInfo["id"];
        unset($shareInfo["id"]);
        $shareInfo["createTime"] = $time;
        $newShareBaseId = $shareBaseModel->add($shareInfo);
        $shareMaterialInfo = $shareMaterModel->where("sId=".$shareBaseId)->find();
        unset($shareMaterialInfo["id"]);
        $shareMaterialInfo["sId"]=$newShareBaseId;
        $shareMaterId = $shareMaterModel->add($shareMaterialInfo);
        Log::write('addsql'.$shareMaterModel->getLastSql());
//        if($shareMaterId){
//            $result = new stdClass();
//            $result->code = 0;
//            $result->productId=$newProductId;
//            return $result;
////            Output::instance()->object($result);
//        }else{
//            Output::instance()->resultCode(code_sql_error);
//            return;
//        }

    }
    //激活商家
    public static function vendorActivate($id){
        $customerId = Session::$user["customerId"];
        $userId= Session::$user["userId"];
        Session::switchCustomer(0);
        $supersetting = M("customer_super_setting");
        $vendorModel =M("mivendor");
        Session::switchCustomer($customerId);
        $vendorLimit = $supersetting->where("customerId=$customerId")->getField("vendorLimit");
        $vendorCount = $vendorModel->where("cId=$customerId and deleted=0")->count();
        if($vendorCount<$vendorLimit){
            $result["id"] = self::addMivendor($userId,$id,1);
            Output::instance()->object($result);
        }else{
            Output::instance()->resultCode(1,"可开通商家数量不足");
        }
    }
    //新建商家门店
    public static function addVendorStore($id,$name,$phone){
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $storeModel = M("store");
        $storeDistrict = M("store_district");
        $category = M("store_district_category");
        Session::switchCustomer($cid);
        $storeId= $storeModel->where("vId=$id and deleted=0")->getField("id");
        $data['name']=$name;
        $data['phone']=$phone;
        $data['customerId']=$cid;
        $data['vId']=$id;
        $data['createTime']=date("Y-m-d H:i:s");
        $data['updateTime'] = date("Y-m-d H:i:s");
        if(!$storeId){
            $categoryId = $category->where("fromCustomerId = $cid and deleted=0 and name='默认'")->getField("id");
            if(!$categoryId){
                $categoryData['name']='默认';
                $categoryData['fromCustomerId']=$cid;
                $categoryData['updateTime']=date("Y-m-d H:i:s");
                $categoryId= $category->add($categoryData);
            }
            $districtId = $storeDistrict->where("fromCustomerId=$cid and deleted=0 and parentId is null and districtCategoryId=$categoryId")->getField("id");
            if(!$districtId){
                $districtData['name'] = '门店信息';
                $districtData['fromCustomerId'] = $cid;
                $districtData['leaf'] = 0;
                $districtData['updateTime'] = date("Y-m-d H:i:s");
                $districtData['districtCategoryId'] = $categoryId;
                $districtId = $storeDistrict->add($districtData);
            }
            $data['districtId']=$districtId;
            $storeModel->add($data);
        }
    }
    //获得商家信息
    public static function getVendorInfo($id){
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $result = $vendorModel->alias("a")
            ->join("wx_".$cid."_user_weixin_info c on a.userId=c.userId")
            ->where("a.id=$id")
            ->field("a.id,a.name,a.phone,c.nickname,c.headimgurl,a.balance")
            ->find();
			$result['balance'] = number_format($result['balance'],2);
        Output::instance()->object($result);
    }
    //修改商家信息
    public static function saveVendorInfo($id,$name,$phone){
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($cid);
        $data['name']=$name;
        $data['phone']=$phone;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $vendorModel->where("id=$id")->save($data);
        self::addVendorStore($id,$name,$phone);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }

}